<template>
  <div id="aiChatView">
    <!-- 聊天消息列表 -->
    <div class="chat-container" v-if="messages.length > 0">
      <div class="message-list" ref="messageList">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="[
            'message-item',
            message.role === 'user' ? 'user-message' : 'ai-message',
          ]"
        >
          <div class="message-avatar">
            <icon-user v-if="message.role === 'user'" />
            <icon-robot v-else />
          </div>
          <div class="message-content">
            <div v-if="message.role === 'assistant'" class="message-text" v-html="formatMessage(message.content)"></div>
            <div v-else class="message-text">{{ message.content }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无消息时的欢迎界面 -->
    <div class="welcome-container" v-if="messages.length === 0">
      <div class="welcome-header">
        <icon-robot class="robot-icon" />
        <h1 class="welcome-title">有什么可以帮你的?</h1>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="input-area">
        <a-input-search
          v-model="inputMessage"
          placeholder="给DeepSeek发送消息"
          :loading="isLoading"
          button-text="发送"
          search-button
          @press-enter="handleSendMessage"
          @search="handleSendMessage"
        >
          <template #button-icon>
            <icon-send />
          </template>
        </a-input-search>
      </div>

      <!-- 快速问题选择区 -->
      <div class="quick-questions">
        <a-button class="question-tag" @click="selectQuestion('写一篇技术博客')">
          <template #icon>
            <icon-edit />
          </template>
          写一篇技术博客
        </a-button>
        <a-button class="question-tag" @click="selectQuestion('解释一个概念')">
          <template #icon>
            <icon-bulb />
          </template>
          解释一个概念
        </a-button>
        <a-button class="question-tag" @click="selectQuestion('代码问题排查')">
          <template #icon>
            <icon-code />
          </template>
          代码问题排查
        </a-button>
        <a-button class="question-tag" @click="selectQuestion('优化代码建议')">
          <template #icon>
            <icon-command />
          </template>
          优化代码建议
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { 
  IconRobot, 
  IconUser, 
  IconEdit, 
  IconBulb, 
  IconCode, 
  IconCommand,
  IconSend
} from "@arco-design/web-vue/es/icon";
import message from "@arco-design/web-vue/es/message";
import { QuestionControllerService } from "../../../generated";
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

interface Message {
  role: "user" | "assistant";
  content: string;
}

const messages = ref<Message[]>([]);
const inputMessage = ref("");
const isLoading = ref(false);
const messageList = ref<HTMLElement | null>(null);

// 选择预设问题
const selectQuestion = (question: string) => {
  inputMessage.value = question;
};

// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim()) {
    message.warning("请输入消息内容");
    return;
  }

  // 添加用户消息
  messages.value.push({
    role: "user",
    content: inputMessage.value,
  });

  const userMessage = inputMessage.value;
  inputMessage.value = "";
  isLoading.value = true;

  try {
    // 使用 QuestionControllerService 发送请求
    const response = await QuestionControllerService.chatUsingPost({
      message: userMessage,
    });

    if (!response || response.code !== 0) {
      throw new Error(response?.message || "请求失败");
    }

    // 添加AI回复
    messages.value.push({
      role: "assistant",
      content: response.data?.content || "AI 无法回应，请稍后再试",
    });
  } catch (error) {
    message.error("发送消息失败，请稍后重试");
    console.error("发送消息失败:", error);
  } finally {
    isLoading.value = false;
    // 滚动到底部
    await nextTick();
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  }
};

// 格式化消息内容，支持代码高亮
const formatMessage = (content: string) => {
  if (!content) return '';
  
  // 处理代码块，格式为 ```language code ```
  return content.replace(/```([\w-]+)?\s*([\s\S]+?)```/g, (match, language, code) => {
    // 如果指定了语言且highlight.js支持该语言
    if (language && hljs.getLanguage(language)) {
      const highlighted = hljs.highlight(code.trim(), { language, ignoreIllegals: true });
      return `<div class="code-block">
                <div class="code-header">
                  <span>${language || 'code'}</span>
                  <div class="code-actions">
                    <button class="copy-btn" onclick="navigator.clipboard.writeText(\`${code.trim()}\`)">复制</button>
                    <button class="download-btn">下载</button>
                  </div>
                </div>
                <pre class="hljs"><code>${highlighted.value}</code></pre>
              </div>`;
    } else {
      // 如果没有指定语言或不支持该语言，尝试自动检测
      const highlighted = hljs.highlightAuto(code.trim());
      return `<div class="code-block">
                <div class="code-header">
                  <span>${language || 'code'}</span>
                  <div class="code-actions">
                    <button class="copy-btn" onclick="navigator.clipboard.writeText(\`${code.trim()}\`)">复制</button>
                    <button class="download-btn">下载</button>
                  </div>
                </div>
                <pre class="hljs"><code>${highlighted.value}</code></pre>
              </div>`;
    }
  });
};

// 页面加载时滚动到底部
onMounted(() => {
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight;
  }
});
</script>

<style scoped>
#aiChatView {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  min-height: calc(100vh - 160px); /* 减小高度，让底部有更多空间 */
  display: flex;
  flex-direction: column;
  padding-bottom: 80px; /* 增加底部内边距 */
}

.welcome-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
  margin-top: -80px; /* 向上移动欢迎界面 */
}

.welcome-header {
  text-align: center;
  margin-bottom: 40px;
}

.robot-icon {
  font-size: 48px;
  color: #165dff;
  margin-bottom: 20px;
}

.welcome-title {
  font-size: 32px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 10px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fc;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e5e6eb;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message-content {
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-message .message-content {
  background-color: #4080ff;
  color: #fff;
}

.input-container {
  margin-top: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  position: relative; /* 设置相对定位 */
  bottom: 20px; /* 向上移动输入区域 */
}

.input-area {
  display: flex;
  gap: 12px;
}

:deep(.arco-input-search) {
  border-radius: 24px;
  padding: 8px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.arco-input-search .arco-input-inner-wrapper) {
  border-radius: 24px;
  background-color: #fff;
}

:deep(.arco-input-search .arco-input-search-button) {
  border-radius: 0 24px 24px 0;
  background-color: #4080ff;
  color: white;
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  margin-top: 16px;
}

.question-tag {
  border-radius: 24px;
  padding: 6px 16px;
  background-color: rgba(64, 128, 255, 0.08);
  color: #4080ff;
  border: 1px solid rgba(64, 128, 255, 0.3);
  cursor: pointer;
  transition: all 0.2s;
}

.question-tag:hover {
  background-color: rgba(64, 128, 255, 0.15);
  border-color: rgba(64, 128, 255, 0.5);
}

.message-text {
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.code-block {
  margin: 12px 0;
  border-radius: 8px;
  overflow: hidden;
  background-color: #282c34;
  color: #abb2bf;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #1e2127;
  color: #abb2bf;
  font-size: 12px;
  border-bottom: 1px solid #3e4451;
}

.code-actions {
  display: flex;
  gap: 8px;
}

.copy-btn, .download-btn {
  background: none;
  border: none;
  color: #abb2bf;
  font-size: 12px;
  cursor: pointer;
  padding: 2px 8px;
  border-radius: 4px;
}

.copy-btn:hover, .download-btn:hover {
  background-color: #3e4451;
}

.hljs {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
  font-size: 14px;
  line-height: 1.5;
  background-color: #282c34 !important;
}
</style>
